import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'

// 公共路由
const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/auth/Login.vue'),
    meta: { guest: true }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/auth/Register.vue'),
    meta: { guest: true }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/user/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/health-data',
    name: 'health-data',
    component: () => import('../views/health/HealthData.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/health-reports',
    name: 'health-reports',
    component: () => import('../views/health/HealthReports.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/ai-assistant',
    component: () => import('../views/ai/AiAssistant.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'ai-assistant',
        component: () => import('../views/ai/AiAssistant.vue')
      },
      {
        path: ':id',
        name: 'ai-assistant-conversation',
        component: () => import('../views/ai/AiAssistant.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isGuest = to.matched.some(record => record.meta.guest)
  const isAuthenticated = store.getters['auth/isAuthenticated']
  
  if (requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (isGuest && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router 